<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>protobuf by websocket</title>
<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.7.3/dist/protobuf.js"></script>
</head>
<body>
body
</body>

<script>
var Message;
protobuf.load("peer.proto", function(err, root) {
    if (err)
        throw err;

    // Obtain a message type
    Message = root.lookupType("abx.protos.Book");

    // Exemplary payload
    var payload = { name: "book88888" };

    // Verify the payload if necessary (i.e. when possibly incomplete or invalid)
    var errMsg = Message.verify(payload);
    if (errMsg)
        throw Error(errMsg);

    // Create a new message
    var message = Message.create(payload); // or use .fromObject if conversion is necessary

    // Encode a message to an Uint8Array (browser) or Buffer (node)
    var buffer = Message.encode(message).finish();
    // ... do something with buffer

    // Decode an Uint8Array (browser) or Buffer (node) to a message
    var message = Message.decode(buffer);
    // ... do something with message

    // If the application uses length-delimited buffers, there is also encodeDelimited and decodeDelimited.

    // Maybe convert the message back to a plain object
    var object = Message.toObject(message, {
        longs: String,
        enums: String,
        bytes: String,
        // see ConversionOptions
    });
});


//Connect to our server: node server.js
var socket = new WebSocket("ws://localhost:8080/feed");
socket.binaryType = "arraybuffer"; // We are talking binary

socket.onopen = function() {
    console.log( "Connected\n");
};

socket.onclose = function() {
	console.log( "Disconnected\n");
};

socket.onmessage = function(evt) {
    try {
    	var ed   = new Uint8Array(evt.data);
        var msg = Message.decode(ed);
        console.log( "Received: "+msg.name+"\n");
    } catch (err) {
    	console.log( "Error: "+err+"\n");
    }
};

function send() {
    if (socket.readyState == WebSocket.OPEN) {
        var msg = new Message(text.value);
        socket.send(msg.toBuffer());
        console.log(  "Sent: "+msg.text+"\n");
    } else {
    	console.log( "Not connected\n");
    }
}
</script>
</html>